using MaterialSkin.Controls;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VideoAutoGenerator.UI.UserControls
{
    public partial class VideoGenerationControl : MaterialCard
    {
        private MaterialLabel titleLabel;
        private MaterialTextBox audioFileTextBox;
        private MaterialButton audioFileButton;
        private MaterialTextBox subtitleFileTextBox;
        private MaterialButton subtitleFileButton;
        private MaterialTextBox imageFolderTextBox;
        private MaterialButton imageFolderButton;
        private MaterialTextBox outputNameTextBox;
        private MaterialLabel outputNameLabel;
        private CheckBox useTransitionEffectCheckBox;
        private CheckBox useAllImagesCheckBox;
        private CheckBox useDatDurationCheckBox;
        private MaterialButton startGenerationButton;
        private MaterialButton stopGenerationButton;
        private ListBox logListBox;
        private Process currentProcess;

        public VideoGenerationControl()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 创建控件
            CreateControls();

            // 设置布局
            SetupLayout();

            // 添加事件处理程序
            SetupEventHandlers();

            this.ResumeLayout(false);
        }

        private void CreateControls()
        {
            titleLabel = new MaterialLabel();
            audioFileTextBox = new MaterialTextBox();
            audioFileButton = new MaterialButton();
            subtitleFileTextBox = new MaterialTextBox();
            subtitleFileButton = new MaterialButton();
            imageFolderTextBox = new MaterialTextBox();
            imageFolderButton = new MaterialButton();
            outputNameTextBox = new MaterialTextBox();
            outputNameLabel = new MaterialLabel();
            useTransitionEffectCheckBox = new CheckBox();
            useAllImagesCheckBox = new CheckBox();
            useDatDurationCheckBox = new CheckBox();
            startGenerationButton = new MaterialButton();
            stopGenerationButton = new MaterialButton();
            logListBox = new ListBox();
        }

        private void SetupLayout()
        {
            // 设置控件属性
            this.AutoScroll = true;
            this.Dock = DockStyle.Fill;
            this.Padding = new Padding(20);

            // 标题
            titleLabel.Text = "视频生成";
            titleLabel.AutoSize = true;
            titleLabel.Font = new Font(titleLabel.Font.FontFamily, 16, FontStyle.Bold);
            titleLabel.Location = new Point(10, 10);

            // 音频文件
            var audioFileLabel = new MaterialLabel();
            audioFileLabel.Text = "音频文件:";
            audioFileLabel.AutoSize = true;
            audioFileLabel.Location = new Point(10, 50);

            audioFileTextBox.Width = 400;
            audioFileTextBox.Location = new Point(120, 48);

            audioFileButton.Text = "浏览";
            audioFileButton.Width = 70;
            audioFileButton.Location = new Point(530, 48);

            // 字幕文件
            var subtitleFileLabel = new MaterialLabel();
            subtitleFileLabel.Text = "字幕文件:";
            subtitleFileLabel.AutoSize = true;
            subtitleFileLabel.Location = new Point(10, 90);

            subtitleFileTextBox.Width = 400;
            subtitleFileTextBox.Location = new Point(120, 88);

            subtitleFileButton.Text = "浏览";
            subtitleFileButton.Width = 70;
            subtitleFileButton.Location = new Point(530, 88);

            // 图片文件夹
            var imageFolderLabel = new MaterialLabel();
            imageFolderLabel.Text = "图片目录:";
            imageFolderLabel.AutoSize = true;
            imageFolderLabel.Location = new Point(10, 130);

            imageFolderTextBox.Width = 400;
            imageFolderTextBox.Location = new Point(120, 128);

            imageFolderButton.Text = "浏览";
            imageFolderButton.Width = 70;
            imageFolderButton.Location = new Point(530, 128);

            // 输出文件名
            outputNameLabel.Text = "输出文件名:";
            outputNameLabel.AutoSize = true;
            outputNameLabel.Location = new Point(10, 170);

            outputNameTextBox.Width = 400;
            outputNameTextBox.Location = new Point(120, 168);

            // 复选框选项
            useTransitionEffectCheckBox.Text = "使用过渡效果";
            useTransitionEffectCheckBox.AutoSize = true;
            useTransitionEffectCheckBox.Location = new Point(120, 200);

            useAllImagesCheckBox.Text = "使用目录下所有图片";
            useAllImagesCheckBox.AutoSize = true;
            useAllImagesCheckBox.Location = new Point(120, 230);

            useDatDurationCheckBox.Text = "使用 DAT 时长";
            useDatDurationCheckBox.AutoSize = true;
            useDatDurationCheckBox.Location = new Point(120, 260);

            // 按钮
            startGenerationButton.Text = "开始生成";
            startGenerationButton.Width = 100;
            startGenerationButton.Location = new Point(120, 300);

            stopGenerationButton.Text = "停止生成";
            stopGenerationButton.Width = 100;
            stopGenerationButton.Location = new Point(230, 300);
            stopGenerationButton.Enabled = false;

            // 日志列表
            var logLabel = new MaterialLabel();
            logLabel.Text = "生成日志:";
            logLabel.AutoSize = true;
            logLabel.Location = new Point(10, 340);

            logListBox.Width = 550;
            logListBox.Height = 200;
            logListBox.Location = new Point(10, 370);
            // MaterialListBox没有BorderStyle属性，移除相关代码

            // 添加控件到面板
            this.Controls.Add(titleLabel);
            this.Controls.Add(audioFileLabel);
            this.Controls.Add(audioFileTextBox);
            this.Controls.Add(audioFileButton);
            this.Controls.Add(subtitleFileLabel);
            this.Controls.Add(subtitleFileTextBox);
            this.Controls.Add(subtitleFileButton);
            this.Controls.Add(imageFolderLabel);
            this.Controls.Add(imageFolderTextBox);
            this.Controls.Add(imageFolderButton);
            this.Controls.Add(outputNameLabel);
            this.Controls.Add(outputNameTextBox);
            this.Controls.Add(useTransitionEffectCheckBox);
            this.Controls.Add(useAllImagesCheckBox);
            this.Controls.Add(useDatDurationCheckBox);
            this.Controls.Add(startGenerationButton);
            this.Controls.Add(stopGenerationButton);
            this.Controls.Add(logLabel);
            this.Controls.Add(logListBox);
        }

        private void SetupEventHandlers()
        {
            audioFileButton.Click += AudioFileButton_Click;
            subtitleFileButton.Click += SubtitleFileButton_Click;
            imageFolderButton.Click += ImageFolderButton_Click;
            startGenerationButton.Click += StartGenerationButton_Click;
            stopGenerationButton.Click += StopGenerationButton_Click;
        }

        private void AudioFileButton_Click(object sender, EventArgs e)
        {
            using (var openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "音频文件|*.mp3;*.wav;*.aac|所有文件|*.*";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    audioFileTextBox.Text = openFileDialog.FileName;
                }
            }
        }

        private void SubtitleFileButton_Click(object sender, EventArgs e)
        {
            using (var openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "字幕文件|*.srt;*.ass;*.dat|所有文件|*.*";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    subtitleFileTextBox.Text = openFileDialog.FileName;
                }
            }
        }

        private void ImageFolderButton_Click(object sender, EventArgs e)
        {
            using (var folderBrowserDialog = new FolderBrowserDialog())
            {
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    imageFolderTextBox.Text = folderBrowserDialog.SelectedPath;
                }
            }
        }

        private async void StartGenerationButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(audioFileTextBox.Text))
            {
                MessageBox.Show("请选择音频文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // 禁用开始按钮，启用停止按钮
            startGenerationButton.Enabled = false;
            stopGenerationButton.Enabled = true;

            // 清空日志
            logListBox.Items.Clear();

            // 添加日志
            AddLog("开始视频生成...");

            try
            {
                // 构建命令行参数
                string args = BuildCommandLineArguments();

                // 调用 Node.js 脚本
                await RunNodeJsScript(args);
            }
            catch (Exception ex)
            {
                AddLog($"生成过程中出现错误: {ex.Message}");
                MessageBox.Show($"生成失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态
                startGenerationButton.Enabled = true;
                stopGenerationButton.Enabled = false;
                AddLog("视频生成完成");
            }
        }

        private string BuildCommandLineArguments()
        {
            // 构建传递给 Node.js 脚本的参数
            var args = $"\"{audioFileTextBox.Text}\"";

            if (!string.IsNullOrEmpty(subtitleFileTextBox.Text))
            {
                args += $" \"{subtitleFileTextBox.Text}\"";
            }

            if (!string.IsNullOrEmpty(imageFolderTextBox.Text))
            {
                args += $" \"{imageFolderTextBox.Text}\"";
            }

            if (!string.IsNullOrEmpty(outputNameTextBox.Text))
            {
                args += $" \"{outputNameTextBox.Text}\"";
            }

            // 添加选项参数
            if (useTransitionEffectCheckBox.Checked)
            {
                args += " --transition";
            }

            if (useAllImagesCheckBox.Checked)
            {
                args += " --all-images";
            }

            if (useDatDurationCheckBox.Checked)
            {
                args += " --dat-duration";
            }

            return args;
        }

        private async Task RunNodeJsScript(string args)
        {
            var processStartInfo = new ProcessStartInfo
            {
                FileName = "node",
                Arguments = $"run_video_with_ffmpeg.js {args}",
                WorkingDirectory = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\.."),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            try
            {
                currentProcess = new Process { StartInfo = processStartInfo };
                
                // 事件处理程序用于捕获输出
                currentProcess.OutputDataReceived += (sender, e) => {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        AddLog(e.Data);
                    }
                };

                currentProcess.ErrorDataReceived += (sender, e) => {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        AddLog($"[错误] {e.Data}");
                    }
                };

                // 启动进程
                currentProcess.Start();

                // 开始异步读取输出
                currentProcess.BeginOutputReadLine();
                currentProcess.BeginErrorReadLine();

                // 等待进程结束
                await Task.Run(() => currentProcess.WaitForExit());
            }
            catch (Exception ex)
            {
                throw new Exception($"无法启动 Node.js 进程: {ex.Message}");
            }
            finally
            {
                currentProcess?.Dispose();
                currentProcess = null;
            }
        }

        private void StopGenerationButton_Click(object sender, EventArgs e)
        {
            if (currentProcess != null && !currentProcess.HasExited)
            {
                try
                {
                    currentProcess.Kill();
                    AddLog("用户终止了视频生成过程");
                }
                catch (Exception ex)
                {
                    AddLog($"无法停止进程: {ex.Message}");
                }
            }
        }

        private void AddLog(string message)
        {
            if (logListBox.InvokeRequired)
            {
                logListBox.Invoke(new Action<string>(AddLog), message);
            }
            else
            {
                logListBox.Items.Add($"[{DateTime.Now:HH:mm:ss}] {message}");
                logListBox.SelectedIndex = logListBox.Items.Count - 1;
                logListBox.TopIndex = logListBox.Items.Count - 1;
            }
        }
    }
}